package cn.coufran.springboot.starter.log.serializer;

import cn.coufran.springboot.starter.log.Mode;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 带缓存的序列化器工厂，相同模式的序列化器不会被重复创建
 * @author Coufran
 * @since 1.0.0
 * @version 1.0.0
 */
public class CachedSerializerFactory implements SerializerFactory {
    /** 原始序列化器工厂 */
    private SerializerFactory serializeFactory;
    /** 序列化器缓存 */
    private final Map<Mode, Serializer> serializers = new ConcurrentHashMap<>();

    /**
     * 构造序列化器工厂
     * @param serializerFactory 原始序列化器工厂
     */
    public CachedSerializerFactory(SerializerFactory serializerFactory) {
        this.serializeFactory = serializerFactory;
    }

    /**
     * 获取序列化器
     * @param mode 序列化模式
     * @return 序列化器
     */
    @Override
    public Serializer getSerializer(Mode mode) {
        Serializer serializer = serializers.get(mode);
        if (serializer == null) {
            synchronized (serializers) {
                serializer = serializers.get(mode);
                if (serializer == null) {
                    serializer = serializeFactory.getSerializer(mode);
                    serializers.put(mode, serializer);
                }
            }
        }
        return serializer;
    }
}
